# -*- coding:utf-8 -*-
from tabulate import tabulate
from colorama import Fore, Style

def handle_pagination(rows, headers, page_size=10):
    max_widths = [len(str(header)) for header in headers]
    for row in rows:
        for i, cell in enumerate(row):
            max_widths[i] = min(50, max(max_widths[i], len(str(cell))))
    
    total_pages = (len(rows) + page_size - 1) // page_size
    current_page = 1

    while True:
        start_idx = (current_page - 1) * page_size
        end_idx = start_idx + page_size
        current_rows = rows[start_idx:end_idx]
        
        print(Fore.CYAN + f"\n--- 第 {current_page}/{total_pages} 页 (共 {len(rows)} 条记录) ---" + Style.RESET_ALL)
        print(Fore.CYAN + tabulate(
            current_rows,
            headers=headers,
            tablefmt='grid',
            maxcolwidths=max_widths
        ) + Style.RESET_ALL)
        
        if total_pages > 1:
            print(Fore.YELLOW + "\n[n]下一页 [p]上一页 [q]退出 [数字]跳转: " + Style.RESET_ALL, end='')
            choice = input().lower()
            
            if choice == 'q':
                break
            elif choice == 'n' and current_page < total_pages:
                current_page += 1
            elif choice == 'p' and current_page > 1:
                current_page -= 1
            elif choice.isdigit():
                page = int(choice)
                if 1 <= page <= total_pages:
                    current_page = page
        else:
            break